/*
 * Copyright (C), 2002-2016, 上海亦寻信息技术有限公司
 * FileName: PinController.java
 * Author:   linyao
 * Date:     2016-6-24 下午3:45:18
 * Description: //模块目的、功能描述      
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */
package com.emm.yixun.website.controller.marketing;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.activiti.engine.IdentityService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.common.enums.ProcessTypeEnums;
import com.emm.yixun.common.model.BaseCodeValue;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.ProjectRoom;
import com.emm.yixun.common.model.Signed;
import com.emm.yixun.common.model.SignedInfo;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.BaseCodeValueDto;
import com.emm.yixun.common.model.dto.BusinessAbnormaDto;
import com.emm.yixun.common.model.dto.HaveReceiveRefundDto;
import com.emm.yixun.common.model.dto.ProjectRoomDto;
import com.emm.yixun.common.model.dto.SignedDto;
import com.emm.yixun.common.model.enums.AuditStatusEnum;
import com.emm.yixun.common.model.enums.BaseCodeTypeEnum;
import com.emm.yixun.common.model.enums.BusinessAbnormaEnum;
import com.emm.yixun.common.model.enums.ContactTypeEnum;
import com.emm.yixun.common.model.enums.DealCategoryEnum;
import com.emm.yixun.common.model.enums.DecorationPaymentMethodEnum;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.model.enums.DocTypeEnum;
import com.emm.yixun.common.model.enums.PaymentMethodEnum;
import com.emm.yixun.common.model.enums.ReceivablesTypeEnum;
import com.emm.yixun.common.model.enums.RoomStatusEnum;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.customer.service.CustomerServiceFacade;
import com.emm.yixun.customer.service.SignedServiceFacade;
import com.emm.yixun.estate.service.ProjectRoomServiceFacade;
import com.emm.yixun.marketing.service.BusinessAbnormaServiceFacade;
import com.emm.yixun.system.service.BaseCodeValueServiceFacade;
import com.emm.yixun.system.service.BusinessLogServiceFacade;
import com.emm.yixun.system.service.MerchantServiceFacade;
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.controller.base.BaseController;
import com.emm.yixun.website.service.ActivitiProcessServiceImpl;
import com.emm.yixun.website.service.ao.DataService.OaDataService;
import com.emm.yixun.website.service.image.WsImageService;
import com.emm.yixun.website.service.marketing.HaveReceiveRefundService;
import com.emm.yixun.website.vo.changeroom.SignedChangeVo;
import com.emm.yixun.website.vo.common.ExtResultVo;

/**
 * 〈一句话功能简述〉 〈功能详细描述〉
 * 
 * @author linyao
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Controller
@RequestMapping("/marketing/changeroom/")
public class ChangeRoomController extends BaseController<Object> {

	
	@Autowired
	private SignedServiceFacade signedServiceFacade;
	@Autowired
	private BusinessAbnormaServiceFacade businessAbnormaServiceFacade;
	@Autowired
	private ProjectRoomServiceFacade projectRoomServiceFacade;
	@Autowired
	private IdentityService identityService;
	@Autowired
	private ActivitiProcessServiceImpl activitiProcessService;
	@Autowired
	private WsImageService wsImageService;
	@Autowired
	private OaDataService oaDataService;
	@Autowired
	private BaseCodeValueServiceFacade baseCodeValueServiceFacade;
	@Autowired
	private MerchantServiceFacade merchantServiceFacade;
	@Autowired
	private HaveReceiveRefundService haveReceiveRefundService;
	@Autowired
	private CustomerServiceFacade customerServiceFacade;
	@Autowired
	private BusinessLogServiceFacade businessLogServiceFacade;
	
	/**
	 * 进入签约换房界面
	 * @return
	 */
	@RequestMapping("signchange")
	public ModelAndView signchange(SignedDto signedDto) {
		//1、判断登录用户是否超时
		//2、登录用户是否拥有权限
		Signed sig = signedServiceFacade.findById(signedDto.getId()).getEntity();
		return new ModelAndView("/marketing/changeroom/signchange")
			.addObject("relationId", signedDto.getId())
			.addObject("userName", ShiroUtil.getCurrentUser().getUserName())
			.addObject("customerId", sig.getCustomerId());
	}
	
	
	/**
	 * 签约换房
	 * 2017-9-21
	 * ym
	 */
	@RequestMapping("signedChangeHouse")
	public String signedChangeHouse(Long signedId,ModelMap map){
		User user = ShiroUtil.getCurrentUser();
		Response<Signed> response=signedServiceFacade.findById(signedId);
		if(response.isSuccess() && null!=response.getEntity()){
			Signed signed=response.getEntity();
			
			String typeName = BaseCodeTypeEnum.getByNo(BaseCodeTypeEnum.TYPE_TWELVE.getNo()).getDes();
			BaseCodeValueDto bcvDto = new BaseCodeValueDto();
			bcvDto.setMerchantId(user.getMerchantId());
			bcvDto.setProjectId(signed.getProjectId());
			bcvDto.setTypeName(typeName);
			bcvDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			// *1解决数字排序问题.例如 1,2,10.排序后会显示成 1,10,2
			bcvDto.setOrders("t.sort*1");
			JSONArray dtArray = JSONArray.parseArray(baseCodeValueServiceFacade.getBcvJsonArray(bcvDto));

			JSONArray pmArray = new JSONArray();
			for (PaymentMethodEnum dt : PaymentMethodEnum.values()) {
				JSONObject row = new JSONObject();
				row.put("value", dt.getNo());
				row.put("name", dt.getDes());
				pmArray.add(row);
			}
			JSONArray ctArray = new JSONArray();
			for (ContactTypeEnum dt : ContactTypeEnum.values()) {
				JSONObject row = new JSONObject();
				row.put("value", dt.getNo());
				row.put("name", dt.getDes());
				ctArray.add(row);
			}
			map.put("contactTypes", ctArray.toJSONString());
			map.put("paymentMethods", pmArray.toJSONString());
			map.put("documentType", dtArray.toJSONString());
			map.put("customerId", signed.getCustomerId());
			map.put("signedId", signedId);
			map.put("currentUserName", user.getUserName());
		}
		return "/customer/signed/signedChangeHouse";
	}
	
	// 新增返回实体对象
	@RequestMapping(value = "signedChangeHouseSave", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes signedChangeHouseSave(String params,Long oldSignedId,HttpServletRequest request) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用新增接口3.返回信息
		 */
		User user = ShiroUtil.getCurrentUser();
		try {
			SignedDto paramsSignedDto = JSONObject.parseObject(params, SignedDto.class);
			Response<ProjectRoom> projectRoomResponse = projectRoomServiceFacade.findById(paramsSignedDto
					.getRoomId());
			Long projectId = projectRoomResponse.getEntity().getProjectId();
			if (null == projectId) {
				ar.setFailMsg("项目不存在!");
				return ar;
			}
			String signedChangeHouseStartProcessKey = "";
			// 动态获取签约审批KEY
			signedChangeHouseStartProcessKey = activitiProcessService.getProcessKey(user.getMerchantId(), projectId,
					ProcessTypeEnums.PROCESS_KEY_14);
			if (StringUtils.isEmpty(signedChangeHouseStartProcessKey)) {
				ar.setFailMsg("项目未设置签约换房审批流程,请去项目流程菜单配置！");
				return ar;
			}
			boolean isSeting = activitiProcessService.checkNodeUser(user.getMerchantId(), projectId, signedChangeHouseStartProcessKey);
			if (!isSeting) {
				ar.setFailMsg("签约换房审批流程节点人员未设置");
				return ar;
			}
			//添加签约记录
			Response<SignedDto> response = signedServiceFacade.addSigned(params, user);
			
			SignedDto signedDto = response.getEntity();
			if (!response.isSuccess()) {
				ar.setFailMsg(response.getResultMessage());
				return ar;
			}
			
			
			Map<String, Object> variables = new HashMap<String, Object>();
			identityService.setAuthenticatedUserId(user.getUserAccount());
			String pid = activitiProcessService.startProcessInstance(user.getMerchantId(), projectId,
					signedChangeHouseStartProcessKey, signedDto.getId().toString(), variables);
			
			//记录异常记录
			BusinessAbnormaDto businessAbnormaDto = new BusinessAbnormaDto();
			businessAbnormaDto.setBusinessId(paramsSignedDto.getOldSignedId());
			businessAbnormaDto.setBusinessType(BusinessAbnormaEnum.BusinessAbnorma_3.getNo());
			businessAbnormaDto.setDelFlag("0");
			businessAbnormaDto.setMerchantId(user.getMerchantId());
			businessAbnormaDto.setAuditStatus(AuditStatusEnum.AUDIT.getNo());
			businessAbnormaDto.setAccessCode(signedDto.getAccessCode());
			businessAbnormaDto.setUserCode(signedDto.getUserCode());
			businessAbnormaDto.setCreateUserId(user.getId());
			businessAbnormaDto.setUpdateUserId(user.getId());
			businessAbnormaDto.setUpdateTime(new Date());
			businessAbnormaDto.setRemark(paramsSignedDto.getSignedChangeHouseRemark());
			businessAbnormaDto.setProcInstId(pid);
			businessAbnormaDto.setNewRoomId(signedDto.getRoomId());
			Response<BusinessAbnormaDto> badResponse=businessAbnormaServiceFacade.save(businessAbnormaDto);
			if(!badResponse.isSuccess()){
				ar.setFailMsg(response.getResultMessage());
				return ar;
			}
			
			SignedDto updateSignedDto = new SignedDto();
			updateSignedDto.setId(signedDto.getId());
			updateSignedDto.setAuditStatus(AuditStatusEnum.AUDIT.getNo());
			updateSignedDto.setProcInstId(pid);
			updateSignedDto.setCheckDate(new Date());
			signedServiceFacade.updateByPrimaryKey(updateSignedDto, true);
			
			// 修改房源状态为认筹
			ProjectRoomDto projectRoomDto = new ProjectRoomDto();
			projectRoomDto.setId(signedDto.getRoomId());
			projectRoomDto.setRoomStatus(RoomStatusEnum.SIGN.getNo());
			projectRoomServiceFacade.updateByPrimaryKey(projectRoomDto, true);
			
			//保存流程附件
			JSONObject paramsObject= JSONObject.parseObject(params);
			String fileUrlArr = paramsObject.getString("fileUrlArr");
			String imageType = paramsObject.getString("imageType");
			wsImageService.uploadAttachment(fileUrlArr, String.valueOf(signedDto.getId()), imageType, signedDto.getAccessCode());
			String resMsg = "换房成功";
			ar.setObj(response.getEntity().getId());
			ar.setRes(Const.SUCCEED);
			ar.setResMsg(resMsg);
		} catch (Exception ex) {
			//新增业务操作异常记录
			businessLogServiceFacade.saveExceptionLog(user, "新增签约换房,不发起流程", params, JSONObject.toJSONString(ex));
			
			logger.error("新增签约换房,不发起流程", ex);
			ar.setFailMsg(Const.SAVE_FAIL);
		}
		return ar;
	}
	
	
	@RequestMapping(value = "changeDetail")
	public String changeDetail(ModelMap map, Long id, String procInstId,String processFlag, String process, HttpServletRequest request,
			String returnUrl) {
		User user = ShiroUtil.getCurrentUser();
		// 认筹开关,默认未关闭(false) ,true已关闭
		boolean payDepositOff = false;
		Response<Boolean> response2 = merchantServiceFacade.merPayDepositOff(user.getMerchantId());
		if (response2.isSuccess()) {
			payDepositOff = response2.getEntity();
		}
		String typeName = BaseCodeTypeEnum.getByNo(BaseCodeTypeEnum.TYPE_TWELVE.getNo()).getDes();
		BaseCodeValueDto bcvDto = new BaseCodeValueDto();
		bcvDto.setMerchantId(user.getMerchantId());
		bcvDto.setTypeName(typeName);
		bcvDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		// *1解决数字排序问题.例如 1,2,10.排序后会显示成 1,10,2
		bcvDto.setOrders("t.sort*1");
		JSONArray dtArray = JSONArray.parseArray(baseCodeValueServiceFacade.getBcvJsonArray(bcvDto));
		//获取支付方式集合
		JSONArray pmArray = new JSONArray();
		for (PaymentMethodEnum dt : PaymentMethodEnum.values()) {
			JSONObject row = new JSONObject();
			row.put("value", dt.getNo());
			row.put("name", dt.getDes());
			pmArray.add(row);
		}
		map.put("paymentMethods", pmArray.toJSONString());
		//获取合同状态集合
		JSONArray ctArray = new JSONArray();
		for (ContactTypeEnum dt : ContactTypeEnum.values()) {
			JSONObject row = new JSONObject();
			row.put("value", dt.getNo());
			row.put("name", dt.getDes());
			ctArray.add(row);
		}
		map.put("contactTypes", ctArray.toJSONString());	
		
		//判断变量id是否是原签约的ID，如为原签约ID，则修改变量id为新签约的ID
		SignedDto signDto = new SignedDto();
		signDto.setOldSignedId(id);
		signDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		ResponseList<Signed> signedListRes = signedServiceFacade.findByDto(signDto);
		if(signedListRes.isSuccess()){
			if(signedListRes.getEntity() != null){
				id = signedListRes.getEntity().get(0).getId();
			}
		}
		
		//查询新签约信息
		Response<SignedInfo> response = signedServiceFacade.findByIdInfo(id);
		String shouStatus = null;
		if (response.isSuccess()) {
			SignedInfo signed = response.getEntity();
			// 收款按钮 已收金额 等于合同金额。不显示
			// 已收金额
			HaveReceiveRefundDto hrrDto = new HaveReceiveRefundDto();
			hrrDto.setRelationId(signed.getId());
			hrrDto.setDocType(DocTypeEnum.COLLECTION.getNo());
			hrrDto.setReceivablesType(ReceivablesTypeEnum.SIGNED.getNo());
			hrrDto.setTransferStatus("0");
			double haveCollection = haveReceiveRefundService.getRealAmount(hrrDto);
			if (new BigDecimal(haveCollection).compareTo(signed.getSignAmount()) == 0) {
				shouStatus = "1";
			} else {
				shouStatus = "0";

			}
			map.put("oldSignedId", signed.getOldSignedId());
			map.put("shouStatus", shouStatus);
			map.put("procInstId", StringUtils.isBlank(procInstId)?signed.getProcInstId():procInstId);
			map.put("auditStatus", signed.getAuditStatus());
			map.put("businessStatus", signed.getBusinessStatus());
			if(signed.getDiscountAfterPrice() == null){
				signed.setDiscountAfterPrice(new BigDecimal("0"));
			}
			SignedInfo signed2 = signed;
			signed2.setExtraInformation("");
			String subscribeStr = JSON.toJSONString(signed2);
			JSONObject signedRecordJson = JSONObject.parseObject(subscribeStr);
			signedRecordJson.put("contactTypeName", StringUtils.isNotBlank(signed.getContactType()) ? ContactTypeEnum
					.getByNo(signed.getContactType()).getDes() : "");
			signedRecordJson.put("decorationPaymentMethodName",
					StringUtils.isNotBlank(signed.getDecorationPaymentMethod())
							? DecorationPaymentMethodEnum.getByNo(signed.getDecorationPaymentMethod()).getDes()
							: "");
			signedRecordJson.put(
					"paymentMethodName",
					StringUtils.isNotBlank(signed.getPaymentMethod()) ? PaymentMethodEnum.getByNo(
							signed.getPaymentMethod()).getDes() : "");
			signedRecordJson.put(
					"dealCategoryName",
					StringUtils.isNotBlank(signed.getDealCategory()) ? DealCategoryEnum.getByNo(
							signed.getDealCategory()).getDes() : "");
			HashMap<String, Double> maps = signedServiceFacade.signedContractAmount(signed.getPayDepositId(),
					signed.getSubscribeId());
			Double payAepositAmount = 0d;
			if(null != maps.get("payAepositAmount")){
				payAepositAmount = maps.get("payAepositAmount");
			}
			signedRecordJson.put("payAepositAmount", payAepositAmount);
			// 判断是否认购转签约，如果是则用已收认购金额-认筹转认购金额
			if (null != signed.getSubscribeId()) {
				Double subscribeAmount = 0d;
				if(null != maps.get("subscribeAmount")){
					subscribeAmount = maps.get("subscribeAmount");
				}
				signedRecordJson.put("subscribeAmount", subscribeAmount - payAepositAmount);
			} else {
				signedRecordJson.put("subscribeAmount", "0");
			}

			map.put("signedRecord", signedRecordJson);
			JSONObject estateRecord = getEstateRecord(signed.getRoomId());
			estateRecord.put("calculateArea", signed.getCalculateArea());
			estateRecord.put("unitPrice", signed.getConversionPrice());
			estateRecord.put("totalPrice", signed.getLumpsumPrice());
			map.put("estateRecord", estateRecord.toJSONString());

			// 已退金额
			hrrDto.setRelationId(signed.getId());
			hrrDto.setDocType(DocTypeEnum.REFUND.getNo());
			hrrDto.setReceivablesType(ReceivablesTypeEnum.SIGNED.getNo());
			double haveRefund = haveReceiveRefundService.getRealAmount(hrrDto);
			// 是否可变更合同 false:不隐藏, true: 隐藏按钮
			boolean contactChange = true;
			if (haveCollection - haveRefund == 0) {
				contactChange = false;
			}
			map.put("contactChangeFlag", contactChange);

			JSONObject customerRecord = getCustomerRecord(signed.getCustomerId());
			map.put("customerRecord", customerRecord);
			// User user =
			// userServiceFacade.findById(signed.getAgentId()).getEntity();
			map.put("userName", signed.getUserName());
		}
		map.put("documentType", dtArray.toJSONString());
		map.put("processFlag", processFlag != null ? processFlag : "false");
		map.put("subscribeId", id);
		map.put("permitBtn", getPermissionBtnArray());
		map.put("process", process);
		map.put("menu", request.getParameter("menu"));
		map.put("payDepositOff", payDepositOff);

		if (!com.alibaba.druid.util.StringUtils.isEmpty(returnUrl)) {
			map.put("returnUrl", returnUrl.replace(",", "/").replace("(", "?").replace(")", "="));
			map.put("returnBackParam", returnUrl);
		}
		return "/customer/signed/signedChangeHouseDetail";
	}

	// 组装房源信息
	public JSONObject getEstateRecord(Long roomId) {
		JSONObject projectRoomJson = new JSONObject();
		Response<ProjectRoom> response = projectRoomServiceFacade.findById(roomId);
		if (response.isSuccess()) {
			ProjectRoom projectRoom = response.getEntity();
			projectRoomJson.put("combinedName", projectRoom.getCombinedName());
			projectRoomJson.put("buildingArea", projectRoom.getBuildingArea());
			projectRoomJson.put("sharingArea", projectRoom.getSharingArea());
			projectRoomJson.put("innerArea", projectRoom.getInnerArea());
			projectRoomJson.put("billingArea", projectRoom.getBillingArea());
			projectRoomJson.put("roomStatusName", StringUtils.isNotBlank(projectRoom.getRoomStatus()) ? RoomStatusEnum
					.getByNo(projectRoom.getRoomStatus()).getDes() : "");
		}
		return projectRoomJson;
	}

	// 组装客户信息
	public JSONObject getCustomerRecord(Long customerId) {
		JSONObject customerJson = new JSONObject();
		Response<Customer> response = customerServiceFacade.findById(customerId);
		if (response.isSuccess()) {
			Customer customer = response.getEntity();
			customerJson.put("customerName", customer.getCustomerName());
			BaseCodeValueDto bcvDto = new BaseCodeValueDto();
			bcvDto.setMerchantId(customer.getMerchantId());
			ResponseList<BaseCodeValue> bcvResList = baseCodeValueServiceFacade.selectListFilterDelFlag(bcvDto);
			Map<Long, String> bcvMap = new HashMap<Long, String>();
			if (bcvResList.isSuccess()) {
				List<BaseCodeValue> bcvList = bcvResList.getEntity();
				for (BaseCodeValue bcv : bcvList) {
					bcvMap.put(bcv.getId(), bcv.getCodeName());
				}
			}
			if (StringUtils.isNotBlank(customer.getPeDocumentType())) {
				customerJson.put("peDocumentTypeName", bcvMap.get(Long.parseLong(customer.getPeDocumentType())));
			}
			customerJson.put("peDocumentNumber", customer.getPeDocumentNumber());
			customerJson.put("customerPhone", customer.getCustomerPhone());
			customerJson.put("peContactAddress", customer.getPeContactAddress());
			customerJson.put("pePostcode", customer.getPePostcode());
			if (StringUtils.isNotBlank(customer.getCustomerOrigin())) {
				customerJson.put("customerOriginName", bcvMap.get(Long.parseLong(customer.getCustomerOrigin())));
			}
		}
		return customerJson;
	}

	
	
	/**
	 * 进入认筹收款界面
	 * @return
	 */
	@RequestMapping("getChangeRecordById")
	public void getChangeRecordById(SignedDto signedDto, HttpServletRequest request, HttpServletResponse response) {
		try {
			ExtResultVo extResultVo = new ExtResultVo();
			extResultVo.setSuccess(false);
			SignedChangeVo signedChangeVo = new SignedChangeVo();
			if(signedDto.getId() == null){
				extResultVo.setErrorMessage("未找到签约记录");
			}else{
				//认筹信息
				Response<SignedDto> resSignedDto = signedServiceFacade.selectChangeSignedByDto(signedDto);
				signedDto = resSignedDto.getEntity();
				if(signedDto != null){
					signedChangeVo.setOld_signCode(signedDto.getSignCode());
					signedChangeVo.setOld_businessType("签约");
					signedChangeVo.setOld_customerName(signedDto.getCustomerName());
					signedChangeVo.setOld_hrrReceived(signedDto.getHrrReceived());
					signedChangeVo.setOld_didTime(signedDto.getDidTime());
					signedChangeVo.setOld_roomName(signedDto.getRoomName());
					signedChangeVo.setOld_calculateArea(signedDto.getCalculateArea());
					signedChangeVo.setOld_conversionPrice(signedDto.getSignPrice());
					signedChangeVo.setOld_lumpsumPrice(signedDto.getLumpsumPrice());
					signedChangeVo.setAgentName(signedDto.getAgentName());//jing'ji'ren
					extResultVo.setSuccess(true);
				}else{
					extResultVo.setErrorMessage("未找到签约记录");
				}
			}
			extResultVo.setData(signedChangeVo);
			resultJson(response, extResultVo);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 提交签约换房
	 * @return
	 */
	@RequestMapping("changeRoomSubmit")
	@ResponseBody
	public AjaxRes changeRoomSubmit(BusinessAbnormaDto businessAbnormaDto) {
		AjaxRes ar = getAjaxRes();
		/*
    	 *1.判断权限 
    	 *2.调用新增接口
    	 *3.返回信息
    	*/
		User user=ShiroUtil.getCurrentUser();
    	try {
			Response<ProjectRoom> projectRoomResponse = projectRoomServiceFacade
					.findById(businessAbnormaDto.getNewRoomId());
			Long projectId = projectRoomResponse.getEntity().getProjectId();
			if (null == projectId) {
				ar.setFailMsg("项目不存在!");
				return ar;
			}
			//动态获取价格方案流程KEY
            String startProcessKey= activitiProcessService.getProcessKey(user.getMerchantId(),projectId,ProcessTypeEnums.PROCESS_KEY_14);
            if(StringUtils.isEmpty(startProcessKey)){
                ar.setFailMsg("项目未设置换房审批流程,请去项目流程菜单配置！");
                return ar;
            }
			String processDefinitionKey=startProcessKey;
			boolean isSeting=activitiProcessService.checkNodeUser(user.getMerchantId(),projectId,processDefinitionKey);
    		if(!isSeting){
    			ar.setFailMsg("换房审批流程节点人员未设置");
    			return ar;
    		}
			Response<BusinessAbnormaDto> response = businessAbnormaServiceFacade.signedChangeRoom(businessAbnormaDto, user);
			if(response.isSuccess()){
				if(response.isSuccess()){
					//启动流程
					identityService.setAuthenticatedUserId(user.getUserAccount());
					String pid=activitiProcessService.startProcessInstance(user.getMerchantId(),projectId,processDefinitionKey,businessAbnormaDto.getBusinessId().toString(), null);
					
					//更新流程ID
					BusinessAbnormaDto update=new BusinessAbnormaDto();
					update.setId(response.getEntity().getId());
					update.setProcInstId(pid);
					update.setAuditStatus(AuditStatusEnum.AUDIT.getNo());
					update.setCheckDate(new Date());
					businessAbnormaServiceFacade.updateByPrimaryKey(update, true);
					
					//保存流程附件
					String fileArr=businessAbnormaDto.getFileArr();
					String imageType = businessAbnormaDto.getImageType();
					if(StringUtils.isNotEmpty(fileArr)){
						//添加流程审核需要的图片
                     	wsImageService.uploadAttachment(fileArr, String.valueOf(businessAbnormaDto.getBusinessId()), imageType, response.getEntity().getAccessCode());
	                }
					
					ar.setSucceed(response.getEntity().getBusinessId());
					ar.setResMsg("换房流程提交成功!");
				}else{
					ar.setRes(0);
					ar.setResMsg(response.getResultMessage());
				}
			}else{
				ar.setRes(0);
				ar.setResMsg(response.getResultMessage());
			}
		} catch (Exception ex) {
			
			//新增业务操作异常记录
			businessLogServiceFacade.saveExceptionLog(user, "新增换房申请", JSONObject.toJSONString(businessAbnormaDto), JSONObject.toJSONString(ex));
			
			
			logger.error("新增换房申请",ex);
			ar.setRes(0);
			ar.setResMsg("签约换房失败,请联系管理员!");
		}
    	return ar;
	}
	
	/**
	* 方法描述 : 详情数据异步加载
	* 项目名称： emm-website
	* 版本： v1.0
	* 创建时间： 2016年7月12日 下午4:53:09
	* @param id
	* @return ExtResultVo
	 */
	@RequestMapping(value = "loadDetailById")
	public void loadDetailById(SignedDto signedDto, HttpServletRequest request, HttpServletResponse response){
		ExtResultVo extResultVo = new ExtResultVo();
		extResultVo.setSuccess(false);
		try {
			SignedChangeVo signedChangeVo = oaDataService.loadSignedChangeRoomInfo(signedDto.getId());
			if(null == signedChangeVo){
				extResultVo.setErrorMessage("未找到签约记录");
			}else{
				extResultVo.setSuccess(true);
			}
			extResultVo.setData(signedChangeVo);
			resultJson(response, extResultVo);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
